package com.yishan.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yishan.security.domain.LoginUser;
import com.yishan.security.domain.User;
import com.yishan.security.mapper.MenuMapper;
import com.yishan.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        //查询不到用户信息 提示错误
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名错误！");
        }
        //查询该用户的相关权限 添加到LoginUser中
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        return new LoginUser(user,list);
    }
}
